package com.subfg.common.util.common;

import com.subfg.common.i18.MessageUtils;
import com.subfg.common.util.auth.AesUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;

@Component
public class ReflectUtil {
    private Logger log = LoggerFactory.getLogger(ReflectUtil.class);

    public String getMessageClassReplceToString(StringBuilder str, Object needClass) {
        Field[] fields = needClass.getClass().getDeclaredFields();
        Long currentTime = System.currentTimeMillis() / 1000;
        Integer length = fields.length;
        try {
            for (int i = 0; i < length; i++)  {
                fields[i].setAccessible(true);
                String nameKey = fields[i].getName();
                String nameKeySuffix = "{" + fields[i].getName() + "}";
                String value = String.valueOf(fields[i].get(needClass));
                if (!nameKey.equals("title") && !nameKey.equals("topContent") && !nameKey.equals("otherUserName")) {
                    if (StringUtil.isEmpty(value)) {
                        if (nameKey.equals("linkUrl")) {
                            value = AesUtil.frontAesEncrypt(value);
                        }
                        String nameKeyTitle = "{" + nameKey + "Title" + "}";
                        str = new StringBuilder(str.toString().replace(nameKeyTitle, MessageUtils.messageTitle(nameKey)));
                        str = new StringBuilder(str.toString().replace(nameKeySuffix, value));
                    }
                } else {
                    if (nameKey.equals("otherUserName")) {
                        str = new StringBuilder(str.toString().replace(nameKeySuffix, String.valueOf(value)));
                    } else {
                        str = new StringBuilder(str.toString().replace(nameKeySuffix, MessageUtils.messageTitle(String.valueOf(value))));
                    }
                }
            }
            Long commplent = System.currentTimeMillis() / 1000 - currentTime;
            log.info("总耗时==>>>"+commplent);
            return str.toString();
        } catch (Exception e) {
            log.error("promet {}", e.getMessage());
            throw new RuntimeException(e);
        }
    }
}
